# pip install PyMySQL 数据库安装，用于爬虫后的数据储存
# 官方文档 https://pymysql.readthedocs.io/en/latest/user/examples.html
import pymysql.cursors

# 官方文档的连接数据库样例代码
connection = pymysql.connect(host='localhost'
                             , user='Toosan'
                             , password='123456'
                             , db='spider_db'
                             , charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
with connection:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        # sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        sql = "SELECT `id`, `password` FROM `users`"
        # cursor.execute(sql, ('webmaster@python.org',))  # 这里的逗号不能省略
        cursor.execute(sql)
        # result = cursor.fetchone()
        result = cursor.fetchall()
        print(result)
